package com.jinwei.qunguanjia.user.service;

import com.jinwei.qunguanjia.common.constant.CacheConstants;
import com.jinwei.qunguanjia.common.constant.Constants;
import com.jinwei.qunguanjia.common.core.domain.model.LoginUser;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.utils.DateUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.common.utils.UUIDUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class UserTokenServiceImpl implements UserTokenService {

    @Resource
    private RedisCache redisCache;

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(LoginUser loginUser)
    {
        String token = UUIDUtils.getUUID();
        loginUser.setToken(token);
        refreshToken(loginUser);
        return token;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    private void refreshToken(LoginUser loginUser)
    {
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        String userNameKey = getUserNameKey(loginUser.getUserName());
        redisCache.setCacheObject(userNameKey, loginUser.getToken(), DateUtils.getOffsetMonth(6), TimeUnit.MILLISECONDS);
        redisCache.setCacheObject(userKey, loginUser, DateUtils.getOffsetMonth(6), TimeUnit.MILLISECONDS);
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    @Override
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(Constants.TOKEN_HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取请求租户id
     *
     * @return 租户id
     */
    @Override
    public String getTenantId(HttpServletRequest request) {
        return request.getHeader(Constants.TENANT_ID_HEADER);
    }

    @Override
    public String getTokenKey(String uuid) {
        return String.format(CacheConstants.DRIVER_LOGIN_TOKEN_KEY) + uuid;
    }

    @Override
    public String getUserNameKey(String userName) {
        return String.format(CacheConstants.DRIVER_LOGIN_USER_NAME_KEY) + userName;
    }
}
